package com.bsoft.gol.hcs.specialist.dao;

import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import com.bsoft.gol.hcs.specialist.bean.request.RueryHistoryMessageReq;
import com.bsoft.gol.hcs.specialist.entity.EasemobChatmessages;
import com.bsoft.gol.hcs.utils.CommonUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @Author:FangZhiyi
 * @Description  聊天记录
 * @Return  
 * @Data Created in 2020/10/13 13:29
 * @Moddified By:
 */
public abstract class EasemobChatmessagesDAO extends HibernateSupportDelegateDAO<EasemobChatmessages> {

    public  Long getHistoryMessageCount(RueryHistoryMessageReq historyMessageReq){
        HibernateStatelessResultAction<Long> action = new AbstractHibernateStatelessResultAction<Long>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getCountHistoryMessage(historyMessageReq);
                Query sqlQuery = getQuery(ss, historyMessageReq, stringBuffer);
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                if (CommonUtils.isNotEmpty(dbList)) {
                    setResult(Long.valueOf(String.valueOf(dbList.get(0).get("countValue"))));
                } else {
                    setResult(0L);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    };
    private StringBuffer getCountHistoryMessage(final RueryHistoryMessageReq historyMessageReq) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT count(1) countValue");
        return getHistoryMessageStringBuffer(stringBuffer, historyMessageReq);
    }
    private StringBuffer getHistoryMessageStringBuffer(StringBuffer stringBuffer,
                                                               final RueryHistoryMessageReq historyMessageReq) {
        stringBuffer.append(" FROM easemob_chatmessages  WHERE  1 = 1");
        if (StringUtils.isNotEmpty(historyMessageReq.getFromUserId())) {
            stringBuffer.append(" and from_user_name=:fromUserId");
        }
        if (StringUtils.isNotEmpty(historyMessageReq.getToUserId())) {
            stringBuffer.append(" and to_user_name=:toUserId");
        }
        if (historyMessageReq.getStartDate()!=null) {
            stringBuffer.append(" and msg_timestamp>=").append(historyMessageReq.getStartDate().getTime());
        }
        if (historyMessageReq.getEndDate()!=null) {
            stringBuffer.append(" and msg_timestamp<=").append(historyMessageReq.getEndDate().getTime());
        }
        return stringBuffer;
    }

    private Query getQuery(StatelessSession ss, final RueryHistoryMessageReq historyMessageReq,
                           StringBuffer stringBuffer) {
        Query sqlQuery = ss.createSQLQuery(stringBuffer.toString());
        if (StringUtils.isNotEmpty(historyMessageReq.getFromUserId())) {
            sqlQuery.setParameter("fromUserId", historyMessageReq.getFromUserId());
        }
        if (StringUtils.isNotEmpty(historyMessageReq.getToUserId())) {
            sqlQuery.setParameter("toUserId", historyMessageReq.getToUserId());
        }
        return sqlQuery;
    }
    public  List<EasemobChatmessages> queryHistoryMessage(RueryHistoryMessageReq historyMessageReq){
        HibernateStatelessResultAction<List<EasemobChatmessages>> action =
                new AbstractHibernateStatelessResultAction<List<EasemobChatmessages>>() {
                    @Override
                    public void execute(StatelessSession ss) {
                        StringBuffer stringBuffer = getColumnHistoryMessageList(historyMessageReq);
                        Query sqlQuery = getQuery(ss, historyMessageReq, stringBuffer);
                        int first = historyMessageReq.getPageNo() > 0 ?
                                (historyMessageReq.getPageNo() - 1) * historyMessageReq.getPageSize() : 0;
                        sqlQuery.setFirstResult(first);
                        sqlQuery.setMaxResults(historyMessageReq.getPageSize());
                        sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                        List<Map> dbList = sqlQuery.list();
                        setResult(mapToList(dbList));
                    }
                };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    private StringBuffer getColumnHistoryMessageList(RueryHistoryMessageReq historyMessageReq){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT msg_id msgId,msg_timestamp msgTimestamp,from_user_name fromUserName," )
                .append("to_user_name toUserName,chat_type toUserName,direction,payload payload ");
        return getHistoryMessageStringBuffer(stringBuffer, historyMessageReq);
    };



    private List<EasemobChatmessages> mapToList(List<Map> maps) {
        List<EasemobChatmessages> executionList = new ArrayList<>();
        for (Map map : maps) {
            executionList.add(ConversionUtils.convert(map, EasemobChatmessages.class));
        }
        return executionList;
    }
}
